﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Longtop.Web.WebSite.Shared;
using Longtop.Web.Linq;

namespace Longtop.Web.WebSite {
    public class ControllerBase : Controller {
        private static MiddleTier s_middleTier = new MiddleTier();

        public virtual MiddleTier MiddleTier {
            get {
                return s_middleTier;
            }
        }

        public virtual ActiveRecordLinqContext ARContext {
            get {
                if (_arContext == null) _arContext = new ActiveRecordLinqContext();
                return _arContext;
            }
        }

        private ActiveRecordLinqContext _arContext;
        private UserIdentity m_identity;
        public virtual UserIdentity Identity {
            get {
                if (this.m_identity == null) {
                    this.m_identity = new UserIdentity() {
                        IsAuthenticated = this.User.Identity.IsAuthenticated,
                        Name = this.User.Identity.Name
                    };
                }

                return this.m_identity;
            }
        }

        protected override ViewResult View(IView view, object model) {
            this.SetIdentityInModel(model);
            return base.View(view, model);
        }

        protected override ViewResult View(string viewName, string masterName, object model) {
            this.SetIdentityInModel(model);
            return base.View(viewName, masterName, model);
        }

        private void SetIdentityInModel(object model) {
            ISiteMasterModel masterModel = model as ISiteMasterModel;
            if (masterModel != null && masterModel.Identity == null) {
                masterModel.Identity = this.Identity;
            }
        }
    }

}
